package test.san.baseproject.base

import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import test.san.baseproject.widet.LoadMoreView

/*
所有上拉加载下拉刷新列表界面的adapter

 */

abstract class BaseListAdapter<ITEMBEAN, ITEMVIEW: View> : RecyclerView.Adapter<BaseListAdapter.BaseListHolder>() {

    private var list = mutableListOf<ITEMBEAN>()

    fun updateList(newList: List<ITEMBEAN>?) {
        newList?.let {
            list.clear()
            list.addAll(it)
            notifyDataSetChanged()
        }
    }

    fun moreList(newList: List<ITEMBEAN>?) {
        newList?.let {
            list.addAll(newList)
            notifyDataSetChanged()
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseListHolder {
        return if (viewType == 1) {
            BaseListHolder(LoadMoreView(parent.context))
        } else {
            BaseListHolder(getItemView(parent.context))
        }
    }

    override fun getItemCount(): Int {
        return list.size + 1
    }

    override fun onBindViewHolder(holder: BaseListHolder, position: Int) {
        if (position == list.size) {
            // 最后一条不需要刷新数据
            return
        }
        val data = list[position]
        val itemView = holder.itemView as ITEMVIEW
        refreshView(itemView, data)
    }

    override fun getItemViewType(position: Int): Int {
        return if (position == list.size) {
            1 // 最后一条
        } else {
            0
        }
    }

    // 刷新条目View
    abstract fun refreshView(itemView: ITEMVIEW, data: ITEMBEAN)
    // 获取条目view
    abstract fun getItemView(context: Context?): ITEMVIEW

    class BaseListHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    }
}